<?php


namespace PKApp\Content;


use PKApp\Content\Classes\LogPushBaiDuService;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Date;

class AdminBaiDuOfPushUrl extends AdminController
{

    private const API = 'http://data.zz.baidu.com/urls';
    private const KEY = 'TokenOfGeneralCollection';
    private $domain, $token;
    protected $list_urls;

    public function Main()
    {
        $params = $this->readConfigFileName('BaiDu');
        if (Arrays::Is($params) && array_key_exists(self::KEY, $params)) {
            $this->token = $params[self::KEY];
        } else {
            $this->noticeByJson('PushBD_ErrApiToken');
        }
        $url_arr = parse_url($this->serviceOfSite()->GetDomain($this->loginUser()->SiteId));
        $this->domain = $url_arr['host'];
        $this->list_urls = cache()->Tmp()->ReadByJSON($this->loginUser()->SiteId . '_' . Date::Format('Y-m-d'), 'LogBaiDuPush');
        if (Arrays::Is($this->list_urls)) {
            $this->_httpPush(Arrays::Column($this->list_urls,'url'));
        } else {
            $this->noticeByJson('PushBD_EmptyUrl');
        }
    }

    private function _httpPush(array $urls)
    {
        $ch = curl_init();
        $options = array(
            CURLOPT_URL => self::API . '?site=' . $this->domain . '&token=' . $this->token,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        $state_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($state_code !== 200) {
            $this->noticeByJson('PushBD_ErrApiCode', 'content', $state_code);
        }
        curl_close($ch);
        // 返回的数据
        $res = json_decode($result, true);
        if (array_key_exists('error', $res)) {
            $this->noticeByJson('PushBD_ErrToken');
        }
        if (array_key_exists('not_same_site', $res)) {
            $this->noticeByJson('PushBD_ErrSiteUrl', 'content', "\n" . urldecode(implode("\n", $res['not_same_site'])));
        }
        $service_log = new LogPushBaiDuService();
        if (array_key_exists('not_valid', $res)) {
            $list_no = $res['not_valid'];
            foreach ($this->list_urls as $index => $item_url) {
                if (in_array($item_url['url'],$list_no)) {
                    unset($this->list_urls[$index]);
                }
            }
            !Arrays::Is($this->list_urls) ?: $service_log->Add($this->list_urls);
            $this->noticeByJson('PushBD_ErrUrl', 'content', "\n" . urldecode(implode("\n", $list_no)));
        }
        if (array_key_exists('success', $res) && array_key_exists('remain', $res)) {
            $service_log->Add($this->list_urls);
            $this->json($res);
        }
    }
}